package com.pds.web.monitor.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pds.common.core.domain.entity.SysRole;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.domain.FileUpload;
import com.pds.system.mapper.FileUploadMapper;
import com.pds.system.mapper.SysUserMapper;
import com.pds.system.service.IFileUploadService;
import com.pds.utils.FileUtil;
import com.pds.web.app.service.IAppMonitorTaskService;
import com.pds.web.app.service.IAppStationOpsService;
import com.pds.web.device.entity.PdsTestOrganizationDevice;
import com.pds.web.device.mapper.PdsTestOrganizationDeviceMapper;
import com.pds.web.monitor.domain.*;
import com.pds.web.monitor.dto.TaskDTO;
import com.pds.web.monitor.mapper.*;
import com.pds.web.monitor.service.IPdsMonitorTaskService;
import com.pds.web.testOrganizationInfo.domain.PdsTestOrganizationInfo;
import com.pds.web.testOrganizationInfo.mapper.PdsTestOrganizationInfoMapper;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("pdsMonitorTaskService")
public class PdsMonitorTaskServiceImpl extends ServiceImpl<PdsMonitorTaskMapper, PdsMonitorTask> implements IPdsMonitorTaskService {

    @Resource
    private PdsMonitorTaskMapper pdsMonitorTaskMapper;
    @Resource
    private PdsMonitorTaskSamplingMapper pdsMonitorTaskSamplingMapper;

    @Resource
    private PdsMonitorTaskAnalysisMapper pdsMonitorTaskAnalysisMapper;

    @Resource
    private PdsMonitorTaskReportMapper pdsMonitorTaskReportMapper;
    @Autowired
    FileUploadMapper fileUploadMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    PdsTestOrganizationInfoMapper testOrganizationInfoMapper;
    @Autowired
    IFileUploadService fileUploadService;

    @Autowired
    PdsTestOrganizationDeviceMapper deviceMapper;
    @Autowired
    IAppMonitorTaskService appMonitorTaskService;
    @Autowired
    IAppStationOpsService appStationOpsService;


    /**
     * 新增检测任务
     * @param pdsMonitorTask
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public PdsMonitorTask addTask(PdsMonitorTask pdsMonitorTask) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        pdsMonitorTask.setStatus("0");
        pdsMonitorTask.setCreateBy(user.getNickName());
        pdsMonitorTask.setCompanyId(user.getDept().getOrganizationId());
        pdsMonitorTask.setCompanyName(user.getDept().getDeptName());
        //根据id查询机构名称，写入任务表，避免查询任务详情时，需关联查询内容太多
        PdsTestOrganizationInfo pdsTestOrganizationInfo = testOrganizationInfoMapper.selectByOrganizationId(pdsMonitorTask.getOrganizationId());
        pdsMonitorTask.setOrganizationName(pdsTestOrganizationInfo.getCompanyName());
        pdsMonitorTaskMapper.insertTask(pdsMonitorTask);
        Date createTime = DateUtils.parseDate(DateUtils.getTime());
        //采样表中增加一条数据
        PdsMonitorTaskSampling pdsMonitorTaskSampling = new PdsMonitorTaskSampling();
        pdsMonitorTaskSampling.setTaskId(pdsMonitorTask.getId());
        pdsMonitorTaskSampling.setCreateBy(pdsMonitorTask.getCreateBy());
        pdsMonitorTaskSampling.setCreateTime(createTime);
        pdsMonitorTaskSampling.setSuperviseId(pdsMonitorTask.getSuperviseId());
        pdsMonitorTaskSampling.setStatus(0);
        //查监督员姓名
        SysUser superviseUser = sysUserMapper.selectUserById(pdsMonitorTask.getSuperviseId());
        pdsMonitorTaskSampling.setSuperviseName(superviseUser.getNickName());
        pdsMonitorTaskSamplingMapper.insert(pdsMonitorTaskSampling);
        //分析表中增加一条数据
        PdsMonitorTaskAnalysis pdsMonitorTaskAnalysis = new PdsMonitorTaskAnalysis();
        pdsMonitorTaskAnalysis.setTaskId(pdsMonitorTask.getId());
        pdsMonitorTaskAnalysis.setCreateTime(createTime);
        pdsMonitorTaskAnalysis.setCreateBy(pdsMonitorTask.getCreateBy());
        pdsMonitorTaskAnalysis.setStatus(0);
        pdsMonitorTaskAnalysisMapper.insert(pdsMonitorTaskAnalysis);
        //报告表中增加一条数据
        PdsMonitorTaskReport pdsMonitorTaskReport = new PdsMonitorTaskReport();
        pdsMonitorTaskReport.setTaskId(pdsMonitorTask.getId());
        pdsMonitorTaskReport.setCreateTime(createTime);
        pdsMonitorTaskReport.setCreateBy(pdsMonitorTask.getCreateBy());
        pdsMonitorTaskReportMapper.insert(pdsMonitorTaskReport);
        return pdsMonitorTask;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public Boolean deleteTask(Long id) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Set<String> role = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        if (!role.contains("enTaskLeader") && !role.contains("testTaskLeader")) {
            throw new Exception("您没有权限，请联系管理员");
        }
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(id);
        //任务权限检测
        checkTask(task,user);
        if(!"0".equals(task.getStatus()) && user.getDept().getType().intValue()==2){
            //已接收状态，企业不能作废
            throw new Exception("任务已接收，请联系检测机构作废");
        }
        if("4,5".contains(task.getStatus()) && user.getDept().getType().intValue()==1){
            //审核中、已完结状态，检测机构不能作废
            throw new Exception("任务在审核中或已完结状态不能作废");
        }
        PdsMonitorTask pdsMonitorTask = new PdsMonitorTask();
        pdsMonitorTask.setId(id);
        pdsMonitorTask.setStatus("7");
        pdsMonitorTask.setUpdateBy(user.getNickName());
        pdsMonitorTaskMapper.updateTask(pdsMonitorTask);
        return true;
    }

    @Override
    public List<Map> listAll(TaskDTO taskDTO) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        //企业、检测机构只能查看自己公司的
        if(user.getDept().getType().intValue()==1 || user.getDept().getType().intValue()==2){
            taskDTO.setDeptId(user.getDept().getOrganizationId());
        }

        Set<String> role = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        if (role.contains("admin")||role.contains("testTaskLeader")||role.contains("enTaskLeader")||role.contains("epbTaskLeader")
                ||role.contains("enAdmin")||role.contains("agencyAdmin")) {
            //检测机构和企业 检测任务负责人查看本公司全部
        }else{
            taskDTO.setUserId(user.getUserId());
        }

        taskDTO.setType(user.getDept().getType());
        List<Map> taskList = pdsMonitorTaskMapper.listAll(taskDTO);
        return taskList;
    }

    @Override
    public Map queryById(Long id) {
        PdsMonitorTask taskInfo = pdsMonitorTaskMapper.queryById(id);
        //查询因子
        if(StringUtils.isNotEmpty(taskInfo.getGuidanceId())) {
            List<String> taskCategory = testOrganizationInfoMapper.getTaskCategory(taskInfo.getGuidanceId());
            taskInfo.setGuidanceList(taskCategory);
        }
        //查询文件信息
        List<Map> fileList = getFileInfo(taskInfo.getContractFileId());
        if(fileList!=null) {
            taskInfo.setContractFile(fileList.get(0));
        }
        //查询采样信息
        QueryWrapper<PdsMonitorTaskSampling> samplingQw = new QueryWrapper<PdsMonitorTaskSampling>();
        samplingQw.eq("task_id", taskInfo.getId());
        PdsMonitorTaskSampling sampling = pdsMonitorTaskSamplingMapper.selectOne(samplingQw);
        //查询文件信息
        String samplingFileIds = sampling.getSamplingEndImgId()+","+sampling.getSamplingBeginImgId()+","+ sampling.getSuperviseImgId();
        List<Map> samplingFileList = getFileInfo(samplingFileIds);
        if(samplingFileList!=null && samplingFileList.size()>0) {
            for (Map map : samplingFileList) {
                if(map.get("fileId").toString().equals(sampling.getSamplingEndImgId())) {
                    sampling.setSamplingEndImg(map);
                }else if(map.get("fileId").toString().equals(sampling.getSamplingBeginImgId())) {
                    sampling.setSamplingBeginImg(map);
                }else if(map.get("fileId").toString().equals(sampling.getSuperviseImgId())) {
                    sampling.setSuperviseImg(map);
                }
            }
        }
        //采样仪器查询
        if(StringUtils.isNotEmpty(sampling.getDeviceIds())){
            List<Map> deviceList = deviceMapper.getListByIds(sampling.getDeviceIds());
            sampling.setDeviceList(deviceList);
        }

        //查询分析信息
        QueryWrapper<PdsMonitorTaskAnalysis> analysisQw = new QueryWrapper<PdsMonitorTaskAnalysis>();
        analysisQw.eq("task_id", taskInfo.getId());
        PdsMonitorTaskAnalysis analysis = pdsMonitorTaskAnalysisMapper.selectOne(analysisQw);
        //分析仪器查询
        if(StringUtils.isNotEmpty(analysis.getDeviceIds())){
            List<Map> deviceList = deviceMapper.getListByIds(analysis.getDeviceIds());
            analysis.setDeviceList(deviceList);
        }
        //照片查询
        String analysisFileIds = analysis.getAnalysisBeginImgId()+","+analysis.getAnalysisEndImgId();
        List<Map> analysisFileList = getFileInfo(analysisFileIds);
        if(analysisFileList!=null && analysisFileList.size()>0) {
            for (Map map : analysisFileList) {
                if (map.get("fileId").toString().equals(analysis.getAnalysisBeginImgId())) {
                    analysis.setAnalysisBeginImg(map);
                } else if (map.get("fileId").toString().equals(analysis.getAnalysisEndImgId())) {
                    analysis.setAnalysisEndImg(map);
                }
            }
        }

        //查询报告信息
        PdsMonitorTaskReport report = getTaskReportByTaskId(taskInfo.getId());

        Map result = new HashMap(4);
        result.put("taskInfo",taskInfo);
        result.put("sampling",sampling);
        result.put("analysis",analysis);
        result.put("report",report);
        return result;
    }

    private PdsMonitorTaskReport getTaskReportByTaskId(Long taskId) {
        QueryWrapper<PdsMonitorTaskReport> reportQw = new QueryWrapper<PdsMonitorTaskReport>();
        reportQw.eq("task_id", taskId);
        PdsMonitorTaskReport report = pdsMonitorTaskReportMapper.selectOne(reportQw);
        //报告附件查询，四种附件一次查询，不然要分四次查
        String reportFileIds = report.getReportResultFileId()+","+report.getSamplingRecordFileId()+","+
                report.getSceneAnalysisFileId()+","+report.getLaboratAnalysisFileId();
        List<Map> reportFileList = getFileInfo(reportFileIds);
        if(reportFileList!=null) {
            List<Map> reportResultFile = new ArrayList<>(reportFileList.size());
            List<Map> samplingRecordFile = new ArrayList<>(reportFileList.size());
            List<Map> sceneAnalysisFile = new ArrayList<>(reportFileList.size());
            List<Map> laboratAnalysisFile = new ArrayList<>(reportFileList.size());
            for (Map map : reportFileList) {
                if(report.getReportResultFileId()!=null
                        && report.getReportResultFileId().contains(map.get("fileId").toString())) {
                    reportResultFile.add(map);
                }else if(report.getSamplingRecordFileId()!=null &&
                        report.getSamplingRecordFileId().contains(map.get("fileId").toString())) {
                    samplingRecordFile.add(map);
                }else if(report.getSceneAnalysisFileId()!=null &&
                        report.getSceneAnalysisFileId().contains(map.get("fileId").toString())) {
                    sceneAnalysisFile.add(map);
                }else if(report.getLaboratAnalysisFileId()!=null &&
                        report.getLaboratAnalysisFileId().contains(map.get("fileId").toString())) {
                    laboratAnalysisFile.add(map);
                }
            }
            report.setReportResultFile(reportResultFile);
            report.setSamplingRecordFile(samplingRecordFile);
            report.setSceneAnalysisFile(sceneAnalysisFile);
            report.setLaboratAnalysisFile(laboratAnalysisFile);
        }
        return report;
    }

    /**
     * 查询文件附件信息
     * @param fileIds
     * @return
     */
    private List<Map> getFileInfo(String fileIds) {
        List<FileUpload> fileUploads = fileUploadMapper.selectFileUploadListByIds(fileIds.split(","));
        if(null == fileUploads || fileUploads.isEmpty()) return null;
        List<Map> result = new ArrayList<>(fileUploads.size());
        for (int i = 0; i < fileUploads.size(); i++) {
            result.add(FileUtil.structureFile(fileUploads.get(i)));
        }
        return result;
    }

    /**
     * 检测机构-检测任务负责人,接收任务、分配人员
     * @param map -taskId 任务ID
     *            -taskCode 任务编码
     *            -guidanceId 检测因子ID，多个逗号分割
     *            -samplerId 采样人员id
     *            -analysisId 分析人员id
     *            reportWriterId 报告撰写人id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void receiveTask(Map map) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String taskId = String.valueOf(map.get("taskId"));
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(Long.parseLong(taskId));
        //任务权限检测
        checkTask(task,user);
        if(!"0".equals(task.getStatus())){
            throw new Exception("任务状态已改变，请刷新页面");
        }
        //添加单号、检测因子
        PdsMonitorTask taskTemp = new PdsMonitorTask();
        taskTemp.setId(task.getId());
        taskTemp.setGuidanceId(String.valueOf(map.get("guidanceId")));
        taskTemp.setTaskCode(String.valueOf(map.get("taskCode")));
        taskTemp.setUpdateBy(user.getNickName());
        taskTemp.setStatus("1");//已接收，待取样
        pdsMonitorTaskMapper.updateTask(taskTemp);
        //添加采样人员
        //查看人员名称，一起写入，避免后面详情查询时，需要查询太多东西
        long samplerId = Long.parseLong(String.valueOf(map.get("samplerId")));
        SysUser samplerUser = sysUserMapper.selectUserById(samplerId);
        PdsMonitorTaskSampling pdsMonitorTaskSampling = new PdsMonitorTaskSampling();
        pdsMonitorTaskSampling.setTaskId(task.getId());
        pdsMonitorTaskSampling.setSamplerName(samplerUser.getNickName());
        pdsMonitorTaskSampling.setSamplerId(samplerId);
        pdsMonitorTaskSampling.setUpdateBy(user.getNickName());
        pdsMonitorTaskSamplingMapper.updateByTaskId(pdsMonitorTaskSampling);
        //添加分析人员
        long analysisId = Long.parseLong(String.valueOf(map.get("analysisId")));
        SysUser analysisUser = sysUserMapper.selectUserById(analysisId);
        PdsMonitorTaskAnalysis pdsMonitorTaskAnalysis = new PdsMonitorTaskAnalysis();
        pdsMonitorTaskAnalysis.setTaskId(task.getId());
        pdsMonitorTaskAnalysis.setUpdateBy(user.getNickName());
        pdsMonitorTaskAnalysis.setAnalysisId(analysisId);
        pdsMonitorTaskAnalysis.setAnalysisName(analysisUser.getNickName());
        pdsMonitorTaskAnalysisMapper.updateByTaskId(pdsMonitorTaskAnalysis);
        //添加报告撰写人
        long reportWriterId = Long.parseLong(String.valueOf(map.get("reportWriterId")));
        SysUser reportWriterUser = sysUserMapper.selectUserById(reportWriterId);
        PdsMonitorTaskReport pdsMonitorTaskReport = new PdsMonitorTaskReport();
        pdsMonitorTaskReport.setTaskId(task.getId());
        pdsMonitorTaskReport.setUpdateBy(user.getNickName());
        pdsMonitorTaskReport.setReportWriterId(reportWriterId);
        pdsMonitorTaskReport.setReportWriter(reportWriterUser.getNickName());
        pdsMonitorTaskReportMapper.updateByTaskId(pdsMonitorTaskReport);

    }

    /**
     * 变更人员配置
     *
     * @param map
     */
    @Override
    public void changeUser(Map map) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long taskId =  Long.parseLong(String.valueOf(map.get("taskId")));
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(taskId);
        //任务权限检测
        checkTask(task,user);
        Set<String> role = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        if (!role.contains("enTaskLeader") && !role.contains("testTaskLeader")) {
            throw new Exception("您没有权限，请联系管理员");
        }
        if(!("0,1").contains(task.getStatus()) && role.contains("enTaskLeader")){
            throw new Exception("采样已结束，不能再修改采样监督员");
        }else if(("0,1").contains(task.getStatus()) && role.contains("enTaskLeader")){
            //修改采样监督员
            if(map.get("superviseId")==null){
                throw new Exception("请选择采样监督员");
            }
            Long superviseId =  Long.parseLong(String.valueOf(map.get("superviseId")));
            SysUser superviseUser = sysUserMapper.selectUserById(superviseId);
            PdsMonitorTaskSampling pdsMonitorTaskSampling = new PdsMonitorTaskSampling();
            pdsMonitorTaskSampling.setTaskId(task.getId());
            pdsMonitorTaskSampling.setSuperviseId(superviseUser.getUserId());
            pdsMonitorTaskSampling.setSuperviseName(superviseUser.getNickName());
            pdsMonitorTaskSampling.setUpdateBy(user.getNickName());
            pdsMonitorTaskSamplingMapper.updateByTaskId(pdsMonitorTaskSampling);
            return;
        }
        if(!"1,2,3".contains(task.getStatus())){
            throw new Exception("采样、分析或报告阶段已结束，不能再修改");
        }

        if("1".equals(task.getStatus())){
            //采样、分析、报告人员都可修改
            if(map.get("samplerId")==null){
                throw new Exception("请选择采样员");
            }
            Long samplerId =  Long.parseLong(String.valueOf(map.get("samplerId")));
            SysUser samplerUser = sysUserMapper.selectUserById(samplerId);
            PdsMonitorTaskSampling pdsMonitorTaskSampling = new PdsMonitorTaskSampling();
            pdsMonitorTaskSampling.setTaskId(task.getId());
            pdsMonitorTaskSampling.setSamplerId(samplerUser.getUserId());
            pdsMonitorTaskSampling.setSamplerName(samplerUser.getNickName());
            pdsMonitorTaskSampling.setUpdateBy(user.getNickName());
            pdsMonitorTaskSamplingMapper.updateByTaskId(pdsMonitorTaskSampling);
        }
        if("(1,2)".contains(task.getStatus())){
            //只能分析、报告人员都可修改
            if(map.get("analysisId")==null){
                throw new Exception("请选择分析员");
            }
            Long analysisId =  Long.parseLong(String.valueOf(map.get("analysisId")));
            SysUser analysisUser = sysUserMapper.selectUserById(analysisId);
            PdsMonitorTaskAnalysis pdsMonitorTaskAnalysis = new PdsMonitorTaskAnalysis();
            pdsMonitorTaskAnalysis.setTaskId(task.getId());
            pdsMonitorTaskAnalysis.setAnalysisId(analysisUser.getUserId());
            pdsMonitorTaskAnalysis.setAnalysisName(analysisUser.getNickName());
            pdsMonitorTaskAnalysis.setUpdateBy(user.getNickName());
            pdsMonitorTaskAnalysisMapper.updateByTaskId(pdsMonitorTaskAnalysis);
        }
        if("(1,2,3)".contains(task.getStatus())){
            //只能报告人员都可修改
            if(map.get("reportWriterId")==null){
                throw new Exception("请选择报告撰写员");
            }
            Long reportWriterId =  Long.parseLong(String.valueOf(map.get("reportWriterId")));
            SysUser reportWriterUser = sysUserMapper.selectUserById(reportWriterId);
            PdsMonitorTaskReport pdsMonitorTaskReport = new PdsMonitorTaskReport();
            pdsMonitorTaskReport.setTaskId(task.getId());
            pdsMonitorTaskReport.setReportWriterId(reportWriterUser.getUserId());
            pdsMonitorTaskReport.setReportWriter(reportWriterUser.getNickName());
            pdsMonitorTaskReport.setUpdateBy(user.getNickName());
            pdsMonitorTaskReportMapper.updateByTaskId(pdsMonitorTaskReport);
        }
    }




    /**
     * 采样提交
     *
     * @param report
     * @param status 2采样提交、3实验室分析提交、4报告提交，进入审核
     */
    @Override
    public void samplingSubmit(PdsMonitorTaskReport report,String status) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(report.getTaskId());
        //任务权限检测
        checkTask(task,user);
        PdsMonitorTaskReport reportDb = new PdsMonitorTaskReport();
        reportDb.setTaskId(report.getTaskId());
        //采样提交
        if("2".equals(status)){
            if(!"1".equals(task.getStatus())) throw new Exception("任务状态已改变，请刷新页面");
            if(StringUtils.isEmpty(report.getSamplingRecordFileId())) throw new Exception("请先上传采样记录文件");
            reportDb.setSamplingRecordFileId(report.getSamplingRecordFileId());
            reportDb.setSceneAnalysisFileId(report.getSceneAnalysisFileId());
        }else if("3".equals(status)) {
            //分析提交
            if(!"2".equals(task.getStatus())) throw new Exception("任务状态已改变，请刷新页面");
            if(StringUtils.isEmpty(report.getLaboratAnalysisFileId())) throw new Exception("请先上传分析记录文件");
            reportDb.setLaboratAnalysisFileId(report.getLaboratAnalysisFileId());
        }else if("4".equals(status)) {
            //报告提交
            if(!"3".equals(task.getStatus())) throw new Exception("任务状态已改变，请刷新页面");
            if(StringUtils.isEmpty(report.getReportResultFileId())) throw new Exception("请先上传检测报告");
            reportDb.setReportResultFileId(report.getReportResultFileId());
            reportDb.setReportDate(new Date());
        }
        reportDb.setUpdateBy(user.getNickName());
        pdsMonitorTaskReportMapper.updateByTaskId(reportDb);
        //更新任务状态为分析中
        PdsMonitorTask taskDb = new PdsMonitorTask();
        taskDb.setId(report.getTaskId());
        taskDb.setStatus(status);
        taskDb.setUpdateBy(user.getNickName());
        pdsMonitorTaskMapper.updateById(taskDb);
    }



    /**
     * 环保局审核
     *
     * @param map - taskId 任务id
     *            - type 1审核通过、2审核退回
     *            - epbScore 评分
     *            - remark 退回原因
     */
    @Override
    public void approve(Map map) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long taskId = Long.parseLong(String.valueOf(map.get("taskId")));
        String type = String.valueOf(map.get("type"));
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(taskId);
        if(!"4".equals(task.getStatus())) throw new Exception("任务状态已改变，请刷新页面");
        PdsMonitorTask temp = new PdsMonitorTask();
        temp.setId(task.getId());
        if("1".equals(type)){
            //审核通过
            if(ObjectUtil.isEmpty(map.get("epbScore"))) throw new Exception("评价分数不能为空");
            temp.setStatus("5");
            temp.setEpbScore(Double.parseDouble(String.valueOf(map.get("epbScore"))));
        }else{
            //审核退回
            temp.setStatus("6");
            if(ObjectUtil.isEmpty(map.get("remark"))) throw new Exception("退回原因不能为空");
        }
        if(ObjectUtil.isNotEmpty(map.get("remark"))) {
            temp.setRemark(String.valueOf(map.get("remark")));
        }
        temp.setUpdateBy(user.getNickName());
        pdsMonitorTaskMapper.updateTask(temp);
    }

    /**
     * 审核退回时，修改任务内容
     *
     * @param map -taskId					任务id
     *            -taskName				任务名称
     *            -taskCode				任务编号
     *            -contractFileId			合同附件ID
     *            -guidanceId				检测因子
     *            -samplingRecordFileId	采样记录文件id,多个用逗号分割
     *            -sceneAnalysisFileId	现场分析记录文件id,多个用逗号分割
     *            -laboratAnalysisFileId	实验室分析记录文件id,多个用逗号分割
     *            -reportResultFileId		检测报告文件id,多个用逗号分割
     * @return
     * @throws Exception
     */
    @Override
    public void edit(Map map) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long taskId = Long.parseLong(String.valueOf(map.get("taskId")));
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(taskId);
        checkTask(task, user);
        if(!task.getStatus().equals("6")) throw new Exception("任务已改变，请刷新页面后重试");
        PdsMonitorTask temp = new PdsMonitorTask();
        temp.setId(taskId);
        if (ObjectUtil.isNotEmpty(map.get("taskName"))) {
            temp.setTaskName(String.valueOf(map.get("taskName")));
        }
        if (ObjectUtil.isNotEmpty(map.get("taskCode"))) {
            temp.setTaskCode(String.valueOf(map.get("taskCode")));
        }
        if (ObjectUtil.isNotEmpty(map.get("contractFileId"))) {
            temp.setContractFileId(String.valueOf(map.get("contractFileId")));
        }
        if (ObjectUtil.isNotEmpty(map.get("guidanceId"))) {
            temp.setGuidanceId(String.valueOf(map.get("guidanceId")));
        }
        temp.setStatus("4");
        temp.setRemark(""); //清除退回原因
        temp.setUpdateBy(user.getNickName());
        pdsMonitorTaskMapper.updateTask(temp);

        PdsMonitorTaskReport report = new PdsMonitorTaskReport();
        report.setTaskId(taskId);
        if (ObjectUtil.isNotEmpty(map.get("samplingRecordFileId"))) {
            report.setSamplingRecordFileId(String.valueOf(map.get("samplingRecordFileId")));
        }
        if (ObjectUtil.isNotEmpty(map.get("sceneAnalysisFileId"))) {
            report.setSceneAnalysisFileId(String.valueOf(map.get("sceneAnalysisFileId")));
        }
        if (ObjectUtil.isNotEmpty(map.get("laboratAnalysisFileId"))) {
            report.setLaboratAnalysisFileId(String.valueOf(map.get("laboratAnalysisFileId")));
        }
        if (ObjectUtil.isNotEmpty(map.get("reportResultFileId"))) {
            report.setReportResultFileId(String.valueOf(map.get("reportResultFileId")));
        }
        report.setUpdateBy(user.getNickName());
        pdsMonitorTaskReportMapper.updateByTaskId(report);


    }

    /**
     * 企业给检测任务评分
     *
     * @param map - taskId 任务id
     *            - enScore 企业评分
     * @return
     * @throws Exception
     */
    @Override
    public void enScore(Map map) throws Exception {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long taskId = Long.parseLong(String.valueOf(map.get("taskId")));
        PdsMonitorTask task = pdsMonitorTaskMapper.queryById(taskId);
        checkTask(task, user);
        if (!task.getStatus().equals("5")) throw new Exception("当前任务未完结，不能评分");
        PdsMonitorTask temp = new PdsMonitorTask();
        temp.setId(taskId);
        if(ObjectUtil.isEmpty(map.get("enScore"))) throw new Exception("请填写评分");
        temp.setEnScore(Double.parseDouble(String.valueOf(map.get("enScore"))));
        temp.setUpdateBy(user.getNickName());
        pdsMonitorTaskMapper.updateTask(temp);
    }

    /**
     * web端首页待办查询
     * 检查任务
     * 运维任务
     *
     * @return
     */
    @Override
    public Map getTask() throws Exception {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String roles = sysUser.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.joining(","));
        //检测任务待办
        Map testTask = getTestTask(sysUser,roles);

        //运维任务待办
        Map opsTask = getOpsTask(sysUser,roles);

        Map result=new HashMap<>(2);
        result.put("testTask",testTask);
        result.put("opsTask",opsTask);

        return result;
    }

    /**
     * 查询统计运维任务待办
     * @param sysUser
     * @param roles
     * @return
     */
    private Map getOpsTask(SysUser sysUser, String roles) {
        Map opsTask = appStationOpsService.getIndexData(null);
        opsTask.remove("stationList");
        opsTask.remove("tableType");
        opsTask.put("taskList",opsTask.get("ongoingList"));
        //企业、运维机构管理员统计数量为本企业全部，环保局查全部
        int type = sysUser.getDept().getType();
        if(type == 0 || type == 1 && roles.contains("opsAdmin")) {
            Map count = pdsMonitorTaskMapper.getOpsTaskCount(type,sysUser.getDept().getOrganizationId());
            opsTask.putAll(count);
        }
        return opsTask;
    }

    /**
     * 查询统计检测任务待办
     * @param sysUser
     * @param roles
     * @return
     * @throws Exception
     */
    private Map getTestTask(SysUser sysUser, String roles) throws Exception {
        Map testTask = appMonitorTaskService.getTaskList(null);
        if(roles.contains("enTaskLeader")||roles.contains("testTaskLeader")
                ||roles.contains("epbTaskLeader")||roles.contains("admin")){
            //企业-检测任务负责人、检测机构-检测任务负责人、环境局-检测任务负责人，数量统计查询全部
            List<Map> taskList = listAll(new TaskDTO());
            if(taskList != null&&!taskList.isEmpty()){
                long approveNum = taskList.stream().filter(item -> item.get("status").toString().equals("4")).count();
                long finishNum = taskList.stream().filter(item -> item.get("status").toString().equals("5")).count();
                testTask.put("totalNum",taskList.size());
                testTask.put("ongoingNum",taskList.size()-approveNum-finishNum);
                testTask.put("approveNum",approveNum);
                testTask.put("finishNum",finishNum);
            }

        }
        List<Map> taskList = (List<Map>) testTask.get("taskList");
        //检测机构-检测任务负责人的接收任务
        if(roles.contains("testTaskLeader")){
            List<Map> list = pdsMonitorTaskMapper.getTestLeaderTask(sysUser.getDept().getOrganizationId());
            if(list != null && !list.isEmpty()) {
                if (taskList != null && !taskList.isEmpty()) {
                    taskList.addAll(list);
                } else {
                    testTask.put("taskList", list);
                }
            }
        }
        //检测机构-报告撰写员的提交和审批退回处理任务
        if(roles.contains("testReportWriter")){
            List<Map> list = pdsMonitorTaskMapper.getTestReportWriterTask(sysUser.getUserId());
            if(list != null && !list.isEmpty()) {
                if (taskList != null && !taskList.isEmpty()) {
                    taskList.addAll(list);
                } else {
                    testTask.put("taskList", list);
                }
            }
        }
        return testTask;
    }

    /**
     * 检测任务权限
     * @param task
     * @param user
     */
    private void checkTask(PdsMonitorTask task, SysUser user) throws Exception {
        if(task==null){
            throw new Exception("此任务不存在");
        }
        if(task.getCompanyId().intValue()!= user.getDept().getOrganizationId().intValue() &&
               task.getOrganizationId().intValue()!= user.getDept().getOrganizationId().intValue())  {
            throw new Exception("此任务不属于您公司，您无权操作");
        }
    }


}
